<template>
  <div
    v-for="(item, index) in list"
    class="div"
    :style="{ backgroundColor: item.background }"
  >
    {{ index }}
  </div>
  <div v-if="isShow" id="circle"></div>
</template>

<script>
import { defineComponent, ref, onMounted, onUnmounted } from "vue";
export default defineComponent({
  name: "List",
  setup() {
    const list =ref([{ background: "rgb(233,32,28)" }])
    const isShow = ref(false);

    function getList(num) {
      return new Promise((res, rej) => {
        let arr = [];
        isShow.value = true;
        for (let i = 0; i < num; i++) {
          arr.push({
            background: `rgb(${parseInt(Math.random() * 255)},${parseInt(
              Math.random() * 255
            )},${parseInt(Math.random() * 255)})`,
          });
        }
        setTimeout(() => res(arr), Math.ceil(Math.random() * 5) * 1000);
      });
    }
    function throttle(fn, delay){
            let timer = null;
            return function(){
                let context = this;
                let args = arguments;
                if(!timer){
                    timer = setTimeout(()=>{
                        timer = null; // 重要
                        fn.apply(context,args)
                    },delay)
                }
            }
        }
    //滚动事件处理函数
    function scrollHandle() {
      console.log("滚了");
      let scollHeight = document.body.scrollHeight;
      let scrollTop =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop;
        if (scrollTop > scollHeight / 2 && list.value.length < 50) {
        getList(10).then((res) => {
          list.value.push(...res);
          isShow.value = false;
          console.log(list.value);
        });
      }
    }
    onMounted(() => {
      //组件挂载时，添加scroll监听
      window.addEventListener("scroll", throttle(scrollHandle,1000), false);
      getList(10).then((res) => {
        // list.value = res;
        list.value=res
        console.log(list)
        isShow.value = false;
      });
    });
    onUnmounted(() => {
      //组件卸载时，停止监听
      window.removeEventListener("scroll", scrollHandle, false);
    });

    return { list, isShow };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.div {
  width: 100%;
  height: 500px;
}
#circle {
  margin: 20px auto;
  width: 100px;
  height: 100px;
  border: 5px white solid;
  border-left-color: #ff5500;
  border-right-color: #0c80fe;
  border-radius: 100%;
  animation: loading1 1s infinite linear;
}
@keyframes loading1 {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
